<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件上传</title>
    <style>
        html,
        body {
            margin: 0;
        }
    </style>
</head>

<body>
    <div class="upload select">
        <input type="file" id="myinput">
        <button onclick="btn()">裁剪</button>
    </div>
    <div>
        <img src="" alt="" style="height: 100vmin;">
    </div>
</body>
<script>
    let myinput = document.getElementById('myinput')
    let file
    let imgEle
    myinput.onchange = function () {
        file = this.files[0]     //获得文件
        console.log('读取到文件信息,这里不是二进制的文件内容', file);
        const formData = new FormData()
        // formData.append('file', file)
        // axios.post('/api/xxx', formData)   // 可以直接用formData上传文件, 浏览器做了处理, 直接把文件信息对应的文件转为了二进制传给接口

        const reader = new FileReader()
        reader.onload = e => {      //监听图片读取完毕
            let url = e.target.result  //获得base64字符串
            console.log(url);
            imgEle = document.getElementsByTagName("img")[0]
            imgEle.src = url
        }
        reader.readAsDataURL(file) //获得图片转的base64字符串, 需要异步监听
    }

    //裁剪=======================================================
    function btn () {
        const cutInfo = {
            x: 30, y: 50, cutWidth: 300, cutHeigth: 300, width: 100, heigth: 100
        }
        const canvas = document.createElement('canvas')
        canvas.width = cutInfo.width
        canvas.heigth = cutInfo.heigth
        const ctx = canvas.getContext('2d')
        ctx.drawImage(          //canvas画图
            imgEle,     //原图
            cutInfo.x,  //截取x
            cutInfo.y,  //截取y
            cutInfo.cutWidth,   //截取宽度
            cutInfo.heigth,     //截取高度
            0,                  //在canvas的x轴开始点画图
            0,                  //在canvas的y轴开始点画图
            cutInfo.width,      //画图缩放宽度
            cutInfo.heigth      //画图缩放高度
        )
        document.body.appendChild(canvas)
        canvas.style.border = '1px solid #ccc'

    // 创建 img 元素并显示裁剪后的图片
    const img = document.createElement('img')
    img.src = canvas.toDataURL('image/jpeg')  // 将 canvas 转换为 base64
    img.alt = '裁剪后的图片'
    
    // 添加样式
    img.style.border = '1px solid #ccc'
    img.style.margin = '10px'
    
    document.body.appendChild(img)


        canvas.toBlob(blob => {     //获得裁剪后的二进制
            const file = new File(
                [blob],  // 可以传入多段二进制,进行组合为文件
                '裁剪后的文件名.jpg',
                {type: 'image/jpeg'}
            )
            console.log(file);     //把blob转化成文件, 这个文件可以传给后端了
        }, 'image/jpeg')
    }


</script>

</html>